package com.ww.scm.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jmesa.facade.TableFacade;
import org.jmesa.limit.ExportType;
import org.jmesa.limit.Limit;
import org.jmesa.limit.RowSelect;
import org.jmesa.view.editor.CellEditor;
import org.jmesa.view.html.HtmlBuilder;
import org.jmesa.view.html.component.HtmlColumn;
import org.jmesa.view.html.component.HtmlRow;
import org.jmesa.view.html.component.HtmlTable;
import org.jmesa.view.html.editor.HtmlCellEditor;
import org.jmesa.view.html.event.RowEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ww.core.component.CustomToolbar;
import com.ww.core.component.CustomView;
import com.ww.core.orm.Page;
import com.ww.core.orm.PropertyFilter;
import com.ww.scm.entity.mat.Bill;
import com.ww.scm.entity.mat.Transaction;
import com.ww.scm.entity.mat.TransactionDetail;
import com.ww.scm.service.StorageManager;

@Controller
@RequestMapping(value = "/bill")
public class BillController {

	private final static String LIST_ACTION = "/bill";  
	
	private final static String BILL_TABLE = "billTable"; 
	private final static String BILL_DETAIL_TABLE = "billDetailTable"; 
	
	
	@Autowired
	private StorageManager storageManager;
	
	public void setStorageManager(StorageManager storageManager) {
		this.storageManager = storageManager;
	}
	
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response) {

		
		return new ModelAndView(LIST_ACTION);
	}
	
	@RequestMapping(value = "/billTable", method = RequestMethod.GET)
	@ResponseBody
	public String bill(HttpServletRequest request,HttpServletResponse response) {
		
		String pageNoPara=request.getParameter(BILL_TABLE+"_p_");
		String pageSizePara=request.getParameter(BILL_TABLE+"_mr_");
		
		TableFacade tableFacade = new TableFacade(BILL_TABLE, request, response);
		int pageNo=1;
		int pageSize=tableFacade.getMaxRows();
		
		if (StringUtils.isNotBlank(pageNoPara)){
			pageNo=Integer.parseInt(pageNoPara);
		}
		if (StringUtils.isNotBlank(pageSizePara)){
			pageSize=Integer.parseInt(pageSizePara);
		}
		tableFacade.setMaxRows(pageSize);
		Page<Bill> page = new Page<Bill>(pageSize);
		page.setPageNo(pageNo);
		
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		//设置默认排序方式
		if (!page.isOrderBySetted()) {
			page.setOrderBy(Page.ORDER_DEFAULT_FIELD);
			page.setOrder(Page.ASC);
		}
		page = storageManager.findBill(page, filters);
		
		
		HtmlTable htmlTable = new HtmlTable();

		HtmlRow htmlRow = new HtmlRow();
		htmlTable.setRow(htmlRow);
		
		
		htmlRow.setOnclick(new RowEvent() {
		      public String execute(Object item, int rowcount) {
		    	  Bill bill=(Bill)item;
		    	  HtmlBuilder html = new HtmlBuilder();
		    	  html.append("onClickAction('"+BILL_TABLE+"','"+rowcount+"','"+bill.getId()+"');");
		    	  return html.toString();
		      }
		});
		
        HtmlColumn checkColumn = new HtmlColumn("id").title("选择");
        checkColumn.setFilterable(false);
        checkColumn.setCellEditor(new CellEditor() {
            public Object getValue(Object item, String property, int rowcount) {
                Bill bill=(Bill)item;
                HtmlBuilder html = new HtmlBuilder();
                html.input().type("checkbox").id(BILL_TABLE+"_checkbox"+String.valueOf(rowcount)).name(BILL_TABLE+"_checkbox").value(bill.getId()).close();
                return html.toString();
            }
        });
        htmlRow.addColumn(checkColumn);		

		HtmlColumn billCode = new HtmlColumn("billCode").title("单据编号");
		billCode.setFilterable(false);
		htmlRow.addColumn(billCode);

		HtmlColumn billDate = new HtmlColumn("billDate").title("单据日期");
		billDate.setFilterable(false);
		htmlRow.addColumn(billDate);

		HtmlColumn operator = new HtmlColumn("operator").title("填报人");
		operator.setFilterable(false);
		htmlRow.addColumn(operator);

		HtmlColumn fillTime = new HtmlColumn("fillTime").title("填报时间");
		fillTime.setFilterable(false);
		htmlRow.addColumn(fillTime);
		
        HtmlColumn id = new HtmlColumn("id").title("操作");
        id.setFilterable(false);
        id.setCellEditor(new CellEditor() {
            public Object getValue(Object item, String property, int rowcount) {
                Object value = new HtmlCellEditor().getValue(item, property, rowcount);
                Bill bill=(Bill)item;
                
                HtmlBuilder html = new HtmlBuilder();
                html.a().href().quote().append("javascript:void(0);").quote().onclick("onDeleteAction('"+BILL_TABLE+"','"+bill.getId()+"');").close();
                html.append("删除");
                html.aEnd();
                html.nbsp();
                html.a().href().quote().append(value).quote().close();
                html.append("编辑");
                html.aEnd();
                return html.toString();
            }
        });
        htmlRow.addColumn(id);
        
        tableFacade.setTable(htmlTable);
        tableFacade.setItems(page.getResult());
        tableFacade.setExportTypes(ExportType.EXCEL,ExportType.PDF);
		tableFacade.setToolbar(new CustomToolbar());
		tableFacade.setView(new CustomView());
		Limit limit=tableFacade.getLimit();
		RowSelect rowSelect=limit.getRowSelect();
		rowSelect.setTotalRows(Integer.valueOf(String.valueOf(page.getTotalItems())));
		rowSelect.setPage(pageNo);
       
		String billTable = tableFacade.render();
        return billTable;
	}
	
	@RequestMapping(value = "/billDetailTable", method = RequestMethod.GET)
	@ResponseBody
	public String billDetail(HttpServletRequest request,HttpServletResponse response) {

		
		TableFacade tableFacade = new TableFacade(BILL_DETAIL_TABLE, request, response);
		
		String billId = request.getParameter("id");

		Bill bill = storageManager.findBillById(billId);
		Transaction lastTransaction=bill.getLastTransaction();
		if (lastTransaction==null){
			return "";
		}
		
		
		HtmlTable htmlTable = new HtmlTable();

		HtmlRow htmlRow = new HtmlRow();
		htmlTable.setRow(htmlRow);
		
		htmlRow.setOnclick(new RowEvent() {
		      public String execute(Object item, int rowcount) {
		    	  TransactionDetail transactionDetail=(TransactionDetail)item;
		    	  HtmlBuilder html = new HtmlBuilder();
		    	  html.append("onClickAction('"+BILL_DETAIL_TABLE+"','"+rowcount+"','"+transactionDetail.getId()+"');");
		    	  return html.toString();
		      }
		});		

		HtmlColumn materielNameColumn = new HtmlColumn("materiel.name").title("物料名称");
		materielNameColumn.setFilterable(false);
		htmlRow.addColumn(materielNameColumn);

		HtmlColumn amountColumn  = new HtmlColumn("amount").title("数量");
		amountColumn.setFilterable(false);
		htmlRow.addColumn(amountColumn);
        
        tableFacade.setTable(htmlTable);
        tableFacade.setItems(lastTransaction.getTransactionDetail());
		tableFacade.setToolbar(new CustomToolbar());
		tableFacade.setView(new CustomView());
       
		String billTable = tableFacade.render();
        return billTable;
	}	
	
	
	
    @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
    @ResponseBody
    public String delete(@PathVariable String id,HttpServletRequest request) {  
    	String operator="";
    	storageManager.deleteBill(id, operator);
    	return "true";
    }
    
    /** 批量删除 */  
    @RequestMapping(method=RequestMethod.DELETE)  
    public String batchDelete(@RequestParam("ids") String[] ids) {  
    	String operator="";
        for(int i = 0; i < ids.length; i++) {  
        	storageManager.deleteBill(ids[i], operator);
        }  
        return "true";
    }   
    
    
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(@PathVariable String id,HttpServletRequest request,HttpServletResponse response) {

		TableFacade tableFacade = new TableFacade(BILL_TABLE, request, response);
		tableFacade.setEditable(true);
		HtmlTable htmlTable = new HtmlTable();

		HtmlRow htmlRow = new HtmlRow();
		htmlTable.setRow(htmlRow);

		HtmlColumn materielNameColumn = new HtmlColumn("materiel.name").title("物料名称");
		materielNameColumn.setFilterable(false);
		htmlRow.addColumn(materielNameColumn);

		HtmlColumn amountColumn  = new HtmlColumn("amount").title("数量");
		amountColumn.setFilterable(false);
		htmlRow.addColumn(amountColumn);
        
        tableFacade.setTable(htmlTable);
		tableFacade.setToolbar(new CustomToolbar());
		tableFacade.setView(new CustomView());
       
		String billTable = tableFacade.render();
        return billTable;
	}
    
	@RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
	public ModelAndView save(@PathVariable String id,HttpServletRequest request,HttpServletResponse response) {

		
		return new ModelAndView(LIST_ACTION);
	}
    
	
	
	
}
